package com.test.travelinformation.fragment;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.test.travelinformation.R;
import com.test.travelinformation.adapter.UpImageAdapter;
import com.test.travelinformation.dao.TravelDao;
import com.test.travelinformation.entity.Travel;
import com.test.travelinformation.utils.GlideEngine;
import com.test.travelinformation.utils.SPUtils;
import com.test.travelinformation.utils.UpImage;
import com.test.travelinformation.utils.UpImageUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;

public class Releasefragment extends Fragment {
    private Button cancel, release;
    private EditText et_messsage;
    private RecyclerView recyclerView;
    private View view;
    private UpImageAdapter adapter;
    private List<String> imageUrls;
    private List<String> upImageUrls;
    private String id;
    private QMUITipDialog tipDialog;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.release_fragment, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        cancel = view.findViewById(R.id.cancel);
        release = view.findViewById(R.id.release);
        recyclerView = view.findViewById(R.id.mRec);
        et_messsage = view.findViewById(R.id.et_messsage);

        tipDialog = new QMUITipDialog.Builder(getContext())
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("发布中...")
                .create();

        Uri uri = Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.mipmap.add_image);
        imageUrls = new ArrayList<>();
        imageUrls.add(uri.toString());
        adapter = new UpImageAdapter(getContext(), imageUrls);
        //单击事件
        adapter.setOnItemClickListener((adapter, v, position) -> {
            if (position == 0) {
                showSelectImage(Releasefragment.this);
            }
        });
        //长按删除
        adapter.setOnItemLongClickListener((adapter1, view1, position) -> {
            if (position > 0) {
                adapter.remove(position);
            }
            return false;
        });
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setAdapter(adapter);


        release.setOnClickListener(v -> {
            if ("".equals(et_messsage.getText().toString()) || TextUtils.isEmpty(et_messsage.getText().toString())) {
                Toast.makeText(getContext(), "请输入描述信息", Toast.LENGTH_SHORT).show();
                et_messsage.setFocusable(true);
                et_messsage.setFocusableInTouchMode(true);
                et_messsage.requestFocus();
            } else {
                new QMUIDialog.MessageDialogBuilder(getContext())
                        .setTitle("发布信息")
                        .setMessage("确认要发布信息吗？")
                        .addAction("取消", (dialog, index) -> dialog.dismiss())
                        .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
                            tipDialog.show();
                            dialog.dismiss();
                            upImageUrls = adapter.getData();
                            upImageUrls.remove(0);
                            UpImageUtils upImageUtils = new UpImageUtils();
                            List<UpImage> urls = upImageUtils
                                    .addImages(upImageUrls)
                                    .up();
                            Log.e("urls", new Gson().toJson(urls));
                            Travel travel = new Travel();
                            travel.setUserId(SPUtils.get(getContext(), "userId", "").toString());
                            travel.setUsername(SPUtils.get(getContext(), "username", "").toString());
                            travel.setDescribe(et_messsage.getText().toString());
                            travel.setImages(new Gson().toJson(urls));
                            travel.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    id = s;
                                    et_messsage.setText("");
//                                    adapter.setNewInstance(new ArrayList<>());
                                    Uri uri = Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.mipmap.add_image);
                                    imageUrls = new ArrayList<>();
                                    imageUrls.add(uri.toString());
                                    adapter.setNewInstance(imageUrls);
                                    tipDialog.dismiss();
                                    Toast.makeText(getContext(), "发布成功", Toast.LENGTH_LONG).show();
                                    PictureFileUtils.deleteAllCacheDirFile(getContext());
                                }
                            });

                        }).create().show();
            }
        });
    }


    /**
     * 打开 图片选择器
     *
     * @param fragment 当前的Fragmnent
     */
    private void showSelectImage(Fragment fragment) {
        PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .isWeChatStyle(true)
                .previewImage(true)
                .compress(true)
                .forResult(new OnResultCallbackListener() {
                    @Override
                    public void onResult(List result) {
                        List<LocalMedia> list = result;
                        for (int i = 0; i < list.size(); i++) {
                            //判断版本，android 10及以上另适配
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                                adapter.addData(list.get(i).getCompressPath());
                                Log.e("路径1", "getPath" + list.get(i).getCompressPath());
                            } else {
                                adapter.addData(list.get(i).getCompressPath());
                            }
                        }
                    }

                    @Override
                    public void onCancel() {
                        //取消
                    }
                });
    }
}
